package com.achilles.fragment;

import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.achilles.activity.MainActivity;
import com.achilles.bean.DataBean;
import com.achilles.bean.ProjectBean;
import com.achilles.callback.IListFragmentChanged;
import com.achilles.callback.IProjectOrGiftDialogItemClick;
import com.achilles.database.DBManager;
import com.achilles.playtask.R;
import com.achilles.utils.DateUtils;
import com.achilles.widget.ProjectOrGiftItemDialog;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * A simple {@link Fragment} subclass.
 */
public class ProjectFragment extends BaseListFragment {

    private IListFragmentChanged IListFragmentChanged;
    private ProjectOrGiftItemDialog mProjectOrGiftItemDialog;

    private Map<Integer,Boolean> mCheckBoxSelect = new HashMap<>();
    private final List<DataBean> mProjectShowList = new ArrayList<>();
    private final Set<DataBean> mProjectSelectSet = new HashSet<>();
    private final List<DataBean> mProjectSelectList = new ArrayList<>();

    public ProjectFragment() {
        // Required empty public constructor
    }

    public static ProjectFragment getInstance(IListFragmentChanged listFragmentChanged) {
        ProjectFragment projectFragment = new ProjectFragment();
        projectFragment.setIListFragmentChanged(listFragmentChanged);
        return projectFragment;
    }

    @Override
    protected int getLayoutID() {
        return R.layout.fragment_project;
    }

    @Override
    protected void onViewCreated(View view) {
        super.onViewCreated(view);
        mProjectOrGiftItemDialog = new ProjectOrGiftItemDialog(getActivity());
        mProjectOrGiftItemDialog.setIProjectOrGiftDialogItemClick(new DialogDialogItemClickOr());

        getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long
                    id) {
                mProjectOrGiftItemDialog.setClickDataBean(mProjectShowList.get(position));
                mProjectOrGiftItemDialog.show();
                return true;
            }
        });
        updateList();
    }

    @Override
    protected View onGetView(int position, int size, DataBean dataBean, View convertView) {
        if (size != mCheckBoxSelect.size()) {
            initCheckBoxSelect(size);
        }
        ProjectBean projectBean = (ProjectBean) dataBean;

        TextView tvProjectType = (TextView) convertView.findViewById(R.id.tvProjectType);
        TextView tvProjectName = (TextView) convertView.findViewById(R.id.tvProjectName);
        TextView tvProjectScore = (TextView) convertView.findViewById(R.id.tvProjectScore);
        TextView tvCompleteTimeTip = (TextView) convertView.findViewById(R.id.tvCompleteTimeTip);
        final CheckBox cbComplete = (CheckBox) convertView.findViewById(R.id.cbProjectComplete);

        cbComplete.setOnCheckedChangeListener(new CbCheckedChange(position, projectBean));
        cbComplete.setChecked(mCheckBoxSelect.get(position));
        tvProjectName.setText(projectBean.getProjectName());
        tvProjectScore.setText(String.valueOf("+" + projectBean.getProjectScore()));

        ProjectBean.ProjectType projectType = projectBean.getProjectType();
        switch (projectType) {
            case Single:{
                tvCompleteTimeTip.setVisibility(View.GONE);
                tvProjectType.setVisibility(View.GONE);
                break;
            }
            case EveryDay:{
                tvCompleteTimeTip.setVisibility(View.VISIBLE);
                tvCompleteTimeTip.setText(String.format(getActivity().getString(R.string
                        .project_complete_time), projectBean.getProjectTimes(), projectBean
                        .getProjectTotalTimes()));
                tvProjectType.setVisibility(View.GONE);
                break;
            }
            case EveryWeek:{
                tvCompleteTimeTip.setVisibility(View.VISIBLE);
                tvCompleteTimeTip.setText(String.format(getActivity().getString(R.string
                        .project_complete_time), projectBean.getProjectTimes(), projectBean
                        .getProjectTotalTimes()));
                tvProjectType.setVisibility(View.VISIBLE);
                tvProjectType.setText(R.string.everyWeek_number_tip);
                break;
            }
            case EveryMonth:{
                tvCompleteTimeTip.setVisibility(View.VISIBLE);
                tvCompleteTimeTip.setText(String.format(getActivity().getString(R.string
                        .project_complete_time), projectBean.getProjectTimes(), projectBean
                        .getProjectTotalTimes()));
                tvProjectType.setVisibility(View.VISIBLE);
                tvProjectType.setText(R.string.everyMonth_number_tip);
                break;
            }
            case Normal:{
                tvCompleteTimeTip.setVisibility(View.VISIBLE);
                tvProjectType.setVisibility(View.VISIBLE);
                int times, totalTime;
                if (projectBean.getProjectTotalTimes() == 1) {
                    times = 0;
                    totalTime = 1;
                } else {
                    times = projectBean.getProjectTimes();
                    totalTime = projectBean.getProjectTotalTimes();
                }
                tvCompleteTimeTip.setText(String.format(getActivity().getString(R.string
                        .project_complete_time), times, totalTime));
                tvProjectType.setText(R.string.normal_tip);
                break;
            }
        }
        return convertView;
    }

    private void initCheckBoxSelect(int size) {
        mCheckBoxSelect = new HashMap<>(size);
        for (int i = 0; i < size; i++) {
            mCheckBoxSelect.put(i, false);
        }
    }

    class CbCheckedChange implements CheckBox.OnCheckedChangeListener {
        private final ProjectBean projectBean;
        private final int position;
        public CbCheckedChange(int position, ProjectBean projectBean) {
            this.position = position;
            this.projectBean = projectBean;
        }

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mCheckBoxSelect.put(position,isChecked);
            if (isChecked) {
                mProjectSelectSet.add(projectBean);
                Log.d("CB","mProjectSelectSet add " + projectBean.toString());
            } else {
                mProjectSelectSet.remove(projectBean);
                Log.d("CB","mProjectSelectSet remove " + projectBean.toString());
            }

            Log.d("CB","mProjectSelectSet" + mProjectSelectSet.size());
            IListFragmentChanged.onHasItemSelected(!mProjectSelectSet.isEmpty());
        }
    }

    @Override
    protected int getListItemLayout() {
        return R.layout.project_list_item;
    }

    @Override
    public void updateList() {
        clearList();
        List<ProjectBean> originProjectBeenList = DBManager.getInstance().queryProjectBeanList();
        
        for (int i = 0; i < originProjectBeenList.size(); i++) {
            ProjectBean projectBean = originProjectBeenList.get(i);
            String projectCompleteDate = projectBean.getProjectCompleteDate();

            if (TextUtils.isEmpty(projectCompleteDate)) {
                mProjectShowList.add(projectBean);
                continue;
            } else if (projectBean.getProjectType() == ProjectBean.ProjectType.Single) {
                continue;
            }

            Date completeDate = new Date(Long.parseLong(projectCompleteDate));
            switch (projectBean.getProjectType()) {
                case Normal:{
                    if (projectBean.isCompleted()) {
                        projectBean = resetProjectData(projectBean);
                    }
                    mProjectShowList.add(projectBean);
                    break;
                }
                case EveryDay: {
                    boolean isTodayComplete = DateUtils.isToday(completeDate);
                    if (!isTodayComplete && projectBean.isCompleted()) {
                        projectBean = resetProjectData(projectBean);
                    }
                    if (!isTodayComplete || (isTodayComplete && !projectBean.isCompleted())) {
                        mProjectShowList.add(projectBean);
                    }
                    break;
                }
                case EveryWeek: {
                    boolean isWeekComplete = DateUtils.isThisWeek(completeDate);
                    if (!isWeekComplete && projectBean.isCompleted()) {
                        projectBean = resetProjectData(projectBean);
                    }
                    if (!isWeekComplete || (isWeekComplete && !projectBean.isCompleted())) {
                        mProjectShowList.add(projectBean);
                    }
                    break;
                }
                case EveryMonth: {
                    boolean isMonthComplete = DateUtils.isThisMonth(completeDate);
                    if (!isMonthComplete && projectBean.isCompleted()) {
                        projectBean = resetProjectData(projectBean);
                    }
                    if (!isMonthComplete || (isMonthComplete && !projectBean.isCompleted())) {
                        mProjectShowList.add(projectBean);
                    }
                    break;
                }
            }

            Log.d("updateList", "projectTotalTimes: " + projectBean.getProjectTotalTimes() + " " +
                    "projectTimes: " + projectBean.getProjectTimes());
        }
        IListFragmentChanged.onHasItemSelected(false);
        notifyListDataChanged(mProjectShowList);
    }

    private void clearList() {
        mProjectSelectList.clear();
        mProjectShowList.clear();
        mProjectSelectSet.clear();
        mCheckBoxSelect.clear();
    }

    @Override
    protected View getEmptyView(View view) {
        return view.findViewById(R.id.emptyView);
    }

    @Override
    protected void onScrollDirectionChanged(boolean isScrollUp) {
        IListFragmentChanged.onListScrollDirectionChanged(isScrollUp);
    }

    public List<DataBean> getSelectProjectList() {
        mProjectSelectList.clear();
        mProjectSelectList.addAll(mProjectSelectSet);
        return mProjectSelectList;
    }

    public void saveCompleteProject(List<DataBean> completeProject,boolean updateScore,boolean updateList) {
        int score = DBManager.getInstance().getScore();
        for (DataBean dataBean : completeProject) {

            String completeDate = String.valueOf(DateUtils.dayBegin(new Date()).getTime());
            String completeSpecificTime = String.valueOf(new Date().getTime());

            ProjectBean projectBean = (ProjectBean) dataBean;

            projectBean.setProjectCompleteDate(completeDate);
            projectBean.setProjectCompleteSpecificTime(completeSpecificTime);
            projectBean.setProjectTimes(projectBean.getProjectTimes() + 1);

            if (projectBean.getProjectType() != ProjectBean.ProjectType.Single) {
                DBManager.getInstance().updateProjectData(projectBean);
            }else {
                DBManager.getInstance().deleteProjectData(projectBean);
            }

            if (projectBean.isCompleted()) {
                score += projectBean.getProjectScore();
                DBManager.getInstance().insertHistoryProjectData(projectBean);
            }
        }
        if (updateScore) {
            DBManager.getInstance().updateUserScore(score);
        }
        if (updateList) {
            updateList();
        }
    }

    private ProjectBean resetProjectData(ProjectBean projectBean) {
        projectBean.setProjectTimes(0);
        System.out.println();
        if (!projectBean.isProjectFixNote()) {
            projectBean.setProjectNote("");
        }
        DBManager.getInstance().updateProjectData(projectBean);
        return projectBean;
    }

    private class DialogDialogItemClickOr implements IProjectOrGiftDialogItemClick {
        @Override
        public void onEditClick(DataBean dataBean) {
            IListFragmentChanged.onCreateViewEdit(MainActivity.FragmentType.ProjectFragment, dataBean);
        }

        @Override
        public void onDeleteClick(DataBean dataBean) {
            Log.d("DialogDialogItemClickOr", "dataBean: " + (dataBean == null));
            DBManager.getInstance().deleteProjectData((ProjectBean) dataBean);
            updateList();
        }
    }

    public void setIListFragmentChanged(IListFragmentChanged IListFragmentChanged) {
        this.IListFragmentChanged = IListFragmentChanged;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.d("AchillesL","setUserVisibleHint: " + isVisibleToUser);
        if (isVisibleToUser) {
            Log.d("AchillesL","mProjectSelectSet.isEmpty(): " + mProjectSelectSet.isEmpty());
            IListFragmentChanged.onHasItemSelected(!mProjectSelectSet.isEmpty());
        }
    }

    @Override
    public void onResume() {
        Log.d("AchillesL","onResume");
        super.onResume();
    }
}
